package net.expectx.pay.merchant.controller;

import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.expectx.common.single.util.MonitorCurrentSystemUtil;
import net.expectx.common.single.util.formatter.MessageFormatter;
import net.expectx.pay.dao.bean.*;
import net.expectx.pay.merchant.common.AdminConstants;
import net.expectx.pay.merchant.common.BaseController;
import net.expectx.pay.rpc.api.MerchantOauthService;
import net.expectx.pay.rpc.api.PaymentChannelService;
import net.expectx.pay.rpc.api.ProductOrderHeaderService;
import net.expectx.pay.rpc.api.SystemTypeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;


/**
 * 后台controller
 *
 * @author jianhun
 * @date 2018/5/17
 */
@Controller
@RequestMapping("/manager/")
@Api(value = "后台管理", description = "后台管理")
public class ManagerController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ManagerController.class);

    @Autowired
    private ProductOrderHeaderService productOrderHeaderService;
    @Autowired
    private PaymentChannelService paymentChannelService;
    @Autowired
    private SystemTypeService systemTypeService;
    @Autowired
    private MerchantOauthService merchantOauthService;


    private static final String SUCCESS_STATUS = "2";
    private static final Long ORDER_TYPE = 12L;

    @ApiOperation(value = "后台首页")
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public ModelAndView index(ModelMap modelMap) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MerchantUser merchantUser=(MerchantUser) session.getAttribute("merchantUser");
        LOGGER.info(MessageFormatter.format("-----------------------{}-------------------------------", "进入首页"));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");

        session.setAttribute("oauthData", merchantOauthService.lookMerchantOauthStatus(merchantUser.getId()));
        return modelAndView;

    }

    @ApiOperation(value = "后台欢迎页")
    @RequestMapping(value = "console", method = RequestMethod.GET)
    public String welcome(ModelMap modelMap) {
        getTradeStatistics(modelMap);
        return "console";
    }

    @RequestMapping(value = "/monitorCurrentSystem", method = RequestMethod.GET)
    @ResponseBody
    public Object monitorCurrentSystem() {
        MonitorCurrentSystemUtil service = new MonitorCurrentSystemUtil();
        MonitorCurrentSystemUtil.MonitorCurrentSystemInfo monitorInfo = service.getMonitorCurrentSystemInfo();
        return monitorInfo;
    }

    /**
     * 获取交易信息
     *
     * @return
     */
    public void getTradeStatistics(ModelMap modelMap) {
        List<TradeStatisticsVO> tradeStatisticsVOList = new ArrayList<>();
        Subject subject = SecurityUtils.getSubject();
        String merchantNo = subject.getSession().getAttribute("merchantNo").toString();
        /**
         * 交易笔数
         * 成功笔数
         * 成交金额
         */
        Long totalSum = 0L;
        Long succSum = 0L;
        BigDecimal bargainSum = new BigDecimal(0);
        /**
         * 订单列表以及本周数据
         */
        long nowTime = System.currentTimeMillis();
        long todayStartTime = nowTime - (nowTime + TimeZone.getDefault().getRawOffset()) % (1000 * 3600 * 24);
        ProductOrderHeaderExample productOrderHeaderExample = new ProductOrderHeaderExample();
        ProductOrderHeaderExample.Criteria criteria = productOrderHeaderExample.createCriteria();
        criteria.andMerchantNoEqualTo(merchantNo);
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        criteria.andOrderDateBetween(todayStartTime, todayStartTime + (1000 * 3600 * 24));
        List<ProductOrderHeader> productOrderHeaders = productOrderHeaderService.selectByExample(productOrderHeaderExample);
        List<ProductOrderHeader> productOrderHeadersWeek = productOrderHeaderService.selectByWeek();
        /***
         * 通道列表
         */
        PaymentChannelExample paymentChannelExample = new PaymentChannelExample();
        paymentChannelExample.createCriteria().andIsDeletedEqualTo(AdminConstants.NO);
        List<PaymentChannel> paymentChannels = paymentChannelService.selectByExample(paymentChannelExample);
        /**
         * 字典组
         */
        SystemTypeExample systemTypeExample = new SystemTypeExample();
        SystemTypeExample.Criteria TypeCriteria = systemTypeExample.createCriteria();
        TypeCriteria.andIsDeletedEqualTo(AdminConstants.NO);
        TypeCriteria.andTypeGroupIdEqualTo(ORDER_TYPE);
        List<SystemType> systemTypes = systemTypeService.selectByExample(systemTypeExample);
        /**
         * 根据类型放入不同list
         * 已typeName为key list为value放入map
         */
        Map<String, List<ProductOrderHeader>> productOrderMap = new HashMap<>();
        for (SystemType systemType : systemTypes) {
            List<ProductOrderHeader> ProductOrderHeaderList = new ArrayList<>();
            for (ProductOrderHeader productOrderHeader : productOrderHeaders) {
                if (systemType.getTypeCode().equals(productOrderHeader.getOrderType())) {
                    ProductOrderHeaderList.add(productOrderHeader);
                }
            }
            if (!ProductOrderHeaderList.isEmpty()) {
                productOrderMap.put(systemType.getTypeName(), ProductOrderHeaderList);
            }
        }
        /**
         * 遍历通道列表
         */
        for (PaymentChannel paymentChannel : paymentChannels) {
            TradeStatisticsVO tradeStatisticsVO = new TradeStatisticsVO("", paymentChannel.getName(), 0L, new BigDecimal(0), 0L, new BigDecimal(0), new BigDecimal(0));
            for (String key : productOrderMap.keySet()) {
                for (ProductOrderHeader productOrderHeader : productOrderMap.get(key)) {
                    if (paymentChannel.getId().equals(Long.valueOf(productOrderHeader.getProductOrderPaymentRecord().getChannelPayway()))) {
                        tradeStatisticsVO.setOrderType(key);
                        tradeStatisticsVO.setGrandTotal(tradeStatisticsVO.getGrandTotal().add(productOrderHeader.getGrandTotal()));
                        tradeStatisticsVO.setSum(tradeStatisticsVO.getSum() + 1);
                        tradeStatisticsVO.setServiceFee(tradeStatisticsVO.getServiceFee().add(productOrderHeader.getServiceFee()));
                        totalSum++;
                        if (SUCCESS_STATUS.equals(productOrderHeader.getOrderStatus())) {
                            tradeStatisticsVO.setSuccessSum(tradeStatisticsVO.getSuccessSum() + 1);
                            tradeStatisticsVO.setSuccessTotal(tradeStatisticsVO.getSuccessTotal().add(productOrderHeader.getGrandTotal()));
                            succSum++;
                            bargainSum.add(productOrderHeader.getGrandTotal());
                        }
                    }
                }
            }
            if (tradeStatisticsVO.getSum() != 0) {
                tradeStatisticsVOList.add(tradeStatisticsVO);
            }
        }
        List daysList = new ArrayList();
        for (ProductOrderHeader productOrderHeader : productOrderHeadersWeek) {
            Map map = new HashMap();
            BigDecimal totalSum1 = productOrderHeader.getTotalSum();
            String days = productOrderHeader.getDays();
            map.put("value", totalSum1);
            map.put("name", days);
            daysList.add(map);
        }
        modelMap.put("tradeStatistics", tradeStatisticsVOList);
        modelMap.put("totalSum", totalSum);
        modelMap.put("succSum", succSum);
        modelMap.put("bargainSum", bargainSum);
        modelMap.addAttribute("daysList", JSONArray.parse(JSONArray.toJSONString(daysList)));
    }
}
